export default {
	state: {
		// list: [{
		// 	id: 1,
		// 	imgUrl: 'https://img11.360buyimg.com/n7/jfs/t1/208356/10/16172/143005/63f26557F9a72a503/de84f94e67cfe0ca.jpg',
		// 	price: 234,
		// 	inventory: 3,
		// 	name: '保持纵横比缩放图片，只保证图片的短边能完全显示出来。也就是说，图片通常只在水平或垂直方向是完整的，另一个方向将会发生截取',
		// 	size: 35,
		// 	color: '红色',
		// 	checked: false,
		// 	num: 10
		// }, {
		// 	id: 2,
		// 	imgUrl: 'https://img11.360buyimg.com/n7/jfs/t1/208356/10/16172/143005/63f26557F9a72a503/de84f94e67cfe0ca.jpg',
		// 	price: 333,
		// 	inventory: 3,
		// 	name: '保持纵横比缩放图片，只保证图片的短边能完全显示出来。也就是说，图片通常只在水平或垂直方向是完整的，另一个方向将会发生截取',
		// 	size: 35,
		// 	color: '红色',
		// 	checked: false,
		// 	num: 11
		// }],
		list: [],
		// 全选中后的id
		selectedList: []
	},
	getters: {
		// 是否全选
		isCheckedAll(state) {
			return state.list.length === state.selectedList.length
		},
		// 结算总价
		totalCount(state) {
			let total = {
				price: 0,
				num: 0
			}
			state.list.forEach(i => {
				if (state.selectedList.indexOf(i.id) > -1) {
					total.price += i.price * i.num
					total.num = state.selectedList.length
				}
			})
			return total
		}
	},
	mutations: {
		initCart(state, list) {
			state.list = list
		},
		// 全选
		checkAll(state) {
			state.selectedList = state.list.map(i => {
				i.checked = true
				return i.id
			})
		},
		// 全不选
		unCheckAll(state) {
			state.list.forEach(v => {
					v.checked = false
				}),
				state.selectedList = []
		},
		// 单选
		checkItem(state, index) {
			let id = state.list[index].id
			let i = state.selectedList.indexOf(id)
			// 点击的数据id已经选中在selectedList中，则删除该项id
			if (i > -1) {
				state.list[index].checked = false
				return state.selectedList.splice(i, 1)
			}
			// 之前没有选中，将当前id添加到selectedList
			state.list[index].checked = true
			return state.selectedList.push(id)
		},
		delGoods(state) {
			state.list = state.list.filter(i => {
				return state.selectedList.indexOf(i.id) === -1
			})
		},
		// 加入购物车
		addShopCart(state, goods) {
			state.list.push(goods)
		}
	},
	actions: {
		// 点击全选
		checkedAll({
			commit,
			getters
		}) {
			getters.isCheckedAll ? commit('unCheckAll') : commit('checkAll')
		}

	}
}
